package com.nl.controller.sms5g.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.global.GlobalConstants;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.MD5;
import com.nl.controller.sms5g.bean.CheckRets;
import com.nl.controller.sms5g.bean.NewTemplateSyncResp;
import com.nl.controller.sms5g.bean.QryTemplateCheckResultResp;
import com.nl.controller.sms5g.bean.Sms5gTemplateInfo;
import com.nl.controller.sms5g.bean.bo.SignExcelData;
import com.nl.controller.sms5g.mapper.Sms5gSignatureMapper;
import com.nl.controller.sms5g.mapper.Sms5gTemplateMapper;
import com.nl.controller.sms5g.service.MailService;
import com.nl.controller.sms5g.service.TimerTaskService;
import com.nl.controller.sms5g.util.DownloadExcel;
import com.nl.controller.sms5g.util.ExcelUtil;
import com.nl.controller.web.mapper.SmsTemplateAttrMapper;
import com.nl.controller.web.util.GZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
public class TimerTaskServiceImpl implements TimerTaskService {

    @Autowired
    private Sms5gTemplateMapper sms5gTemplateMapper;


    @Autowired
    private MailService mailService;

    @Autowired
    private Sms5gSignatureMapper sms5gSignatureMapper;


    /**
     * 自动接收邮件
     */
    @Override
    //@Scheduled(cron="0/30 * * * * ?")
    public void receiveMail() throws MessagingException {
        log.info("----开始接收邮件------");
        Properties  props = new Properties();
        //指定邮件发送协议  只接受邮件是可以不要写的
        props.put("mail.transport.protocol", "smtp");
        //指定邮件接收协议
        props.put("mail.store.protocol", "imap");
        //指定支持SMTP协议的Transport具体类，允许由第三方提供
        props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
        //指定支持IMAP协议的Store具体类，允许由第三方提供
        props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");
        //以上这4个可以全部写上

        //指定采用SMTP协议的邮件发送服务器的IP地址或主机名
        props.put("mail.smtp.host",  "pop.163.com");

        //注意你的服务器的地址
        //网易一共有这三个地址   pop.163.com  imap.163.com  stmp.163.com

        // 设置环境信息
        Session session = Session.getInstance(props);
        //指定接收邮件协议
        Store store = session.getStore("pop3");

        store.connect("pop.163.com","17856941469@163.com", "NGLPNSJMQWJHDOGC");
        //            网易邮箱的服务器地址   账号  密码

        //获得名为默认"inbox"的邮件夹当你自己有定义其他的邮件夹也可以写上去
        Folder folder=store.getFolder("inbox");

        //打开邮件夹
        //它是一个邮件文件夹类。Folder类有两个常见的属性，READ_ONLY表示只读，READ_WRITE表示其内容可读可写
        folder.open(Folder.READ_ONLY);

        //获得邮件夹中的邮件数目
        System.out.println("你一共有:"+folder.getMessageCount()+" 封邮件");

        //获得邮件夹中的未读邮件数目
        System.out.println("你一共有:"+folder.getUnreadMessageCount()+" 未读邮件");
        System.out.println("你一共删除了 "+folder.getDeletedMessageCount()+" 封邮件");

        for(int i=1;i<=folder.getMessageCount();i++){

            Message msg=folder.getMessage(i);
            System.out.println("========================================");
            //获得邮件的发送者、主题和正文
            if(msg.getFrom()[0].toString().contains("<")){
                System.out.println("邮件来自:"+msg.getFrom()[0].toString().substring(msg.getFrom()[0].toString().lastIndexOf("<")+1, msg.getFrom()[0].toString().lastIndexOf(">")));
            }else{
                System.out.println("邮件来自:"+msg.getFrom()[0]);
            }
            System.out.println("邮件主题:" + msg.getSubject());
            System.out.println("发送日期:" + msg.getSentDate());
            String type=msg.getContentType().toString().substring(0, msg.getContentType().toString().indexOf(";"));
            System.out.println("邮件类型:"+type);
            //multipart  当文件类型为multipart/* 时不能正确显示
            System.out.println("邮件内容:"+msg.getContentType().toString());
            if(type.equals("text/html")){
                //请你根据文件的类型来更改文件的解析方式  text/html  multipart/alternative表示复合类型
            }
            InternetAddress[] address = (InternetAddress[]) msg.getFrom();
            //这个是发邮件人的地址
            String from = address[0].getAddress();
            if (from == null) {
                from = "";
            }
            //这个是发邮件的人的姓名
            String personal = address[0].getPersonal();
            if (personal == null) {
                personal = "";
            }
            String fromaddr = personal + "<" + from + ">";
            System.out.println("邮件作者："+fromaddr);
            System.out.println("========================================\r\n");
        }



    }

    @Override
//    @Scheduled(cron="0/30 * * * * ?")
    public void qryTemplateCheckResult() {
        try{
            List<String> modeIdList = sms5gTemplateMapper.qryUncheckedTemplate();
            String ts = "";
            String sign = "";
            String ydStatus = "";
            String ydreason = "";

            if(!CollectionUtils.isEmpty(modeIdList)){
                for(String modeId : modeIdList){
                    JSONObject req = new JSONObject();

                    Date nowDate = new Date();
                    //时间戳精确到秒
                    ts = String.valueOf(nowDate.getTime()/1000);

                    sign = modeId + ts + GlobalConstants.SMS_5G_APP_KEY + GlobalConstants.SMS_5G_APP_SECRET;
                    //进行urlencode加密
                    sign = URLEncoder.encode(sign,"UTF-8");
                    //md5加密
                    MD5 md5 = new MD5();
                    sign = md5.getMD5ofStr(sign);
                    sign = sign.toLowerCase();

                    req.put("appKey", GlobalConstants.SMS_5G_APP_KEY);
                    req.put("modeId",modeId);
                    req.put("ts",ts);
                    req.put("sign",sign);
                    String resp = CommonService.httpPostWithJson(GlobalConstants.SMS_5G_MODE_CHECK_RESULT_URL,req);
                    if (!StringUtils.isEmpty(resp)) {
                        //解压
                        //resp = GZipUtil.gunzip(resp);
                        log.info("qryTemplateCheckResult interface response:" + resp);
                        //resp = "{\"resultCode\":\"0\",\"stationIds\":\"11111:933992,3929393:999393,93939:333333,999024:121211\",\"mgrId\":\"1000001961\"}";
                        JSONObject respJson = JSONObject.parseObject(resp);
                        QryTemplateCheckResultResp qryTemplateCheckResultResp = JSONObject.toJavaObject(respJson, QryTemplateCheckResultResp.class);
                        String resultCode = qryTemplateCheckResultResp.getCode();
                        if(resultCode.equals(GlobalConstants.SUCCESS_STRING)){
                            CheckRets rets = qryTemplateCheckResultResp.getRets();
                            ydStatus = rets.getYdStatus();
                            ydreason = rets.getYdreason();
//                            ltStatus = rets.getLtStatus();
//                            ltreason = rets.getLtreason();
//                            dxStatus = rets.getDxStatus();
//                            dxreason = rets.getDxreason();
                            System.out.println("----"+modeId+"---"+ydStatus);
                            //hy模板状态，0待审核，1审核中，2审核通过，3审核不通过
                            //审核不通过
                            if("4".equals(ydStatus)){
                                ydStatus = "3";
                            }
                            //变更审核状态
                            sms5gTemplateMapper.updateModeCheckState(modeId,ydStatus,ydreason);
                        }

                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public void sendCheckEmail() {
        List<SignExcelData> list = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();
        try {
            log.info("-------start send signature check email--------");
            list = sms5gSignatureMapper.qryEmailRecord();
            if(CollectionUtils.isEmpty(list)){
                log.info("暂无需发邮件");
            }else{
                //上传excel签名申请表格
                map = DownloadExcel.getMember(list);
                String excelFileName = ExcelUtil.createExcel(map);
                //发送邮件
                sendEmail(list,excelFileName);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void sendEmail(List<SignExcelData> list,String excelFileName) throws MessagingException {


        //梅和超--18755585253@139.com
        //创建一个配置文件保存并读取信息
        Properties properties = new Properties();

        //设置qq邮件服务器
        properties.setProperty("mail.host","smtp.163.com");
        //设置发送的协议
        properties.setProperty("mail.transport.protocol","smtp");
        //设置用户是否需要验证
        properties.setProperty("mail.smtp.auth", "true");


        //=================================准备工作完毕

        //1.创建一个session会话对象；
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("17856941469@163.com", "NGLPNSJMQWJHDOGC");
            }
        });

        //可以通过session开启Dubug模式，查看所有的过程
        session.setDebug(false);


        //2.获取连接对象，通过session对象获得Transport，需要捕获或者抛出异常；
        Transport tp = session.getTransport();

        //3.连接服务器,需要抛出异常；
        tp.connect("smtp.163.com","17856941469@163.com","NGLPNSJMQWJHDOGC");


        //4.连接上之后我们需要发送邮件；
        MimeMessage mimeMessage = mailService.sendAccessoryMail(session,list,excelFileName);

        //5.发送邮件
        tp.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //6.关闭连接
        tp.close();
    }


//        //??????
//        String host="smtp.163.com";
//        String userName="17856941469@163.com";
//        String passWord="NGLPNSJMQWJHDOGC";
//
//        //?????
//        Properties properties=new Properties();
//
//        //??qq?????
//        properties.setProperty("mail.host","smtp.163.com");
//        //???????
//        properties.setProperty("mail.transport.protocol","smtp");
//        //??????????
//        properties.setProperty("mail.smtp.auth", "true");
//
//        //??????
//        Session session= Session.getDefaultInstance(properties);
//        session.setDebug(false);
//        String  fileName=null;
//        try {
//            //????????
//            Store store = session.getStore("pop3");
//            //???????
//            store.connect("smtp.163.com",25,"17856941469@163.com","loved1314abc");
//            //store.connect(host,userName,passWord);
//            // ?????????
//            Folder folder=store.getFolder("INBOX");
//            if (folder == null) {
//                log.info("??????????");
//            }
//            // ????????????????
//            folder.open(Folder.READ_WRITE);
//            Calendar calendar=Calendar.getInstance();
//            calendar.add(Calendar.DATE,-1);
//            Date mondayDate = calendar.getTime();
//            SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.GT, mondayDate);
//            SearchTerm address=new SubjectTerm( "MU Report");
//            SearchTerm comparisonAndTerm = new AndTerm(address, comparisonTermLe);
//            Message[] messages = folder.search(comparisonAndTerm);
//            for(int i = 0 ; i < messages.length ; i++){
//                MimeMessage msg = (MimeMessage) messages[i];
//                String subject = msg.getSubject();
//                log.info("----??-----"+subject);
//                //???????
//                /*boolean isContainerAttachment = isContainAttachment(msg);
//                if (isContainerAttachment) {
//                    //????
//                    fileName=saveAttachment(msg,"E:/mail");
//                    //?????????????????
//                    //msg.setFlag(Flags.Flag.DELETED, true);
//                }
//                if(!isContainerAttachment) {
//                    continue;
//                }*/
//            }
//            folder.close(true);
//            store.close();
//            //parseTxtService.readTxt(fileName);
//        }catch (NoSuchProviderException e){
//            log.error("????????:{}",e);
//        }catch (MessagingException e){
//            log.error("???????????:{}",e);
//        }catch (IllegalStateException e){
//            log.error("????????:{}",e);
//        }
//    }
    /**
     * ???????????
     * @return ?????????true??????false
     * @throws MessagingException
     * @throws IOException
     */
/*    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType(Constants.MULTI_PART)) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) ||
                        disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType(Constants.MULTI_PART)) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf(Constants.APPLICATION_CONTEXT) != -1) {
                        flag = true;
                    }
                    if (contentType.indexOf(Constants.NAME_CONTEXT) != -1) {
                        flag = true;
                    }
                }
                if (flag){
                    break;
                }
            }
        } else if (part.isMimeType(Constants.MESSAGE_RFC)) {
            flag = isContainAttachment((Part)part.getContent());
        }
        return flag;
    }
    *//**
     * ????
     * @param part ?????????????????
     * @param destDir  ??????
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     *//*
    public  String saveAttachment(Part part, String destDir) throws UnsupportedEncodingException,
            MessagingException, FileNotFoundException, IOException {
        String fileName=null;
        if (part.isMimeType(Constants.MULTI_PART)) {
            Multipart multipart = (Multipart) part.getContent();    //?????
            //????????????
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //???????????????
                BodyPart bodyPart = multipart.getBodyPart(i);
                //???????????????????????
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase
                        (Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                    fileName=decodeText(bodyPart.getFileName());
                } else if (bodyPart.isMimeType(Constants.MULTI_PART)) {
                    saveAttachment(bodyPart,destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf(Constants.NAME_CONTEXT) != -1 || contentType.indexOf
                            (Constants.APPLICATION_CONTEXT) != -1) {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                        fileName=decodeText(bodyPart.getFileName());
                    }
                }
            }
        } else if (part.isMimeType(Constants.MESSAGE_RFC)) {
            saveAttachment((Part) part.getContent(),destDir);
        }
        return fileName;
    }
    *//**
     * ????????????????
     * @param is ???
     * @param fileName ???
     * @param destDir ??????
     * @throws FileNotFoundException
     * @throws IOException
     *//*
    private  void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        if(fileName.contains(Constants.TXT_SUFIXX)) {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(new File(destDir + fileName)));
            int len = -1;
            while ((len = bis.read()) != -1) {
                bos.write(len);
                bos.flush();
            }
            bos.close();
            bis.close();
        }
    }*/
}